package com.farm.wcp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.farm.category.service.ClasstypeServiceInter;
import com.farm.category.service.TagServiceInter;
import com.farm.core.ParameterService;
import com.farm.core.page.ViewMode;
import com.farm.core.time.TimeTool;
import com.farm.learn.service.ClasschapterServiceInter;
import com.farm.learn.service.ClasshourServiceInter;
import com.farm.learn.service.ClasstServiceInter;
import com.farm.learn.service.TopServiceInter;
import com.farm.learn.service.UserPopServiceInter;
import com.farm.learn.service.UserclassServiceInter;
import com.farm.parameter.FarmParameterService;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.social.domain.AppbindObj;
import com.farm.social.domain.AppbindResource;
import com.farm.social.domain.Outsys;
import com.farm.social.domain.ex.ResourceView;
import com.farm.social.service.AppbindobjServiceInter;
import com.farm.social.service.AppbindresourceServiceInter;
import com.farm.social.service.OutsysServiceInter;
import com.farm.util.web.FarmFormatUnits;
import com.farm.wcp.client.WcpClient;
import com.farm.wcp.client.WcpDataClient;
import com.farm.wcp.client.domain.ApiResult;
import com.farm.wcp.client.utils.WdasJsonMap;
import com.farm.web.WebUtils;
import com.wcp.question.service.QuestionServiceInter;
import com.wts.client.WtsExamClient;
import com.wts.client.utils.WtcJsonMap;

/**
 * 课程创建
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/resourceweb")
@Controller
public class ResourceWebController extends WebUtils {
	@Resource
	private QuestionServiceInter questionServiceImpl;
	private static final Logger log = Logger.getLogger(ResourceWebController.class);
	@Resource
	private ClasstypeServiceInter classTypeServiceImpl;
	@Resource
	private ClasstServiceInter classTServiceImpl;
	@Resource
	private ClasschapterServiceInter classChapterServiceImpl;
	@Resource
	private ClasshourServiceInter classHourServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private TopServiceInter topServiceImpl;
	@Resource
	private UserPopServiceInter userPopServiceImpl;
	@Resource
	private TagServiceInter tagServiceImpl;
	@Resource
	private UserclassServiceInter userClassServiceImpl;
	@Resource
	private OutsysServiceInter outsysServiceImpl;
	@Resource
	private AppbindobjServiceInter appbindObjServiceImpl;
	@Resource
	private AppbindresourceServiceInter appbindResourceServiceImpl;

	/**
	 * 课程查看
	 * 
	 * @return
	 */
	@RequestMapping("/PubtoResource")
	public ModelAndView view(String id, HttpSession session, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		try {
			AppbindResource bindResource = appbindResourceServiceImpl.getAppbindresourceEntity(id);
			Outsys bindSys = outsysServiceImpl.getOutsysEntity(bindResource.getSysid());
			AppbindObj bindObj = appbindObjServiceImpl.getAppbindobjEntity(bindResource.getObjid());
			ResourceView rview = appbindObjServiceImpl.getVisteResource(bindResource.getId(), bindObj.getAppid(),
					bindObj.getApptype(), bindResource.getResourcetype(), bindSys.getBaseurl(),
					bindResource.getResourceurl(), bindResource.getTitle(), bindResource.getNote());
			return view.returnRedirectOnlyUrl(rview.getUrl());
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}
	}

	/**
	 * 资源加载
	 * 
	 * @return
	 */
	@RequestMapping("/PubLoad")
	public ModelAndView load(String resourceid, HttpSession session, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		try {
			AppbindResource bindResource = appbindResourceServiceImpl.getAppbindresourceEntity(resourceid);
			Outsys bindSys = outsysServiceImpl.getOutsysEntity(bindResource.getSysid());
			AppbindObj bindObj = appbindObjServiceImpl.getAppbindobjEntity(bindResource.getObjid());
			ResourceView rview = appbindObjServiceImpl.getVisteResource(bindResource.getId(), bindObj.getAppid(),
					bindObj.getApptype(), bindResource.getResourcetype(), bindSys.getBaseurl(),
					bindResource.getResourceurl(), bindResource.getTitle(), bindResource.getNote());
			List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
			if (rview.getModel().equals("WTS")
					&& (rview.getResourcetype().equals("3") || rview.getResourcetype().equals("4"))) {
				ParameterService config = FarmParameterService.getInstance();
				// 考试
				view.putAttr("tip:4", "考试");
				view.putAttr("tip:3", "测试");
				WtsExamClient wtsConfig = new WtsExamClient(config.getParameter("config.lwts.api.base.url"),
						config.getParameter("config.lwts.api.secret"), config.getParameter("config.lwts.api.loginname"),
						config.getParameter("config.lwts.api.password"));
				WtcJsonMap room = wtsConfig.getRoom(bindResource.getResourceurl(), false);

				String pointinif = "";
				float maxpoint = 0;
				if (getCurrentUser(session) != null) {
					WtcJsonMap backcards = wtsConfig.getCards(room.getString("DATA", "uuid"), null,
							getCurrentUser(session).getLoginname(), "LIVE");
					List<WtcJsonMap> cards = backcards.getList("DATA", "list");
					if (cards.size() <= 0) {
						backcards = wtsConfig.getCards(room.getString("DATA", "uuid"), null,
								getCurrentUser(session).getLoginname(), "HIS");
						cards = backcards.getList("DATA", "list");
					}
					if (cards.size() > 0) {
						for (WtcJsonMap card : cards) {
							float point = card.getFloat("POINT");
							if (maxpoint < point) {
								maxpoint = point;
								pointinif = "&nbsp;<b style='color:green;'>得分：" + (int) point + "分&nbsp;|&nbsp;"
										+ TimeTool.getFormatTimeDate12(card.getString("SUBMITTIME"), "yyyy-MM-dd HH:mm")
										+ "</b>";
							}
						}
					}
				}
				{
					Map<String, Object> node = new HashMap<String, Object>();
					node.put("TITLE", room.getString("DATA", "name") + pointinif);
					String note = "<b>状态</b>:" + room.getString("DATA", "pstatetitle");
					// "pshowtype":"答卷展示类型,1 :标准答題,2:抽卷答題,3:练习,4:学习",
					note = note + "&nbsp;<b>类型</b>:"
							+ FarmFormatUnits.formatDic("1:标准答題,2:抽卷答題,3:练习,4:学习", room.getString("DATA", "pshowtype"));
					note = note + "&nbsp;<b>答题时间</b>:" + room.getString("DATA", "timelen") + "分";
					node.put("NOTE", note);
					node.put("LINK", rview.getUrl());
					node.put("rview", rview);
					datas.add(node);
				}
			}

			if (rview.getModel().equals("WCP")) {
				ParameterService config = FarmParameterService.getInstance();
				WcpDataClient wcpConfig = new WcpDataClient(config.getParameter("config.wcp.api.base.url") + "/api",
						config.getParameter("config.wcp.api.secret"), config.getParameter("config.wcp.api.loginname"),
						config.getParameter("config.wcp.api.password"));
				if (rview.getResourcetype().equals("1")) {
					// 知识库
					view.putAttr("tip", "知识库");
					ApiResult result = wcpConfig.getKnows(bindResource.getResourceurl(), null, null, null, 50);

					for (WdasJsonMap data : result.getData()) {
						Map<String, Object> node = new HashMap<String, Object>();
						node.put("TITLE", data.getObject("TITLE"));
						String note = data.getString("DOCDESCRIBE");
						if (note != null && note.length() > 128) {
							note = note.substring(0, 128) + "...";
						}
						node.put("NOTE", note);
						node.put("LINK", rview.getBaseurl() + "/webdoc/view/Pub" + data.getObject("ID") + ".html");
						node.put("rview", rview);
						datas.add(node);
					}
				}

				if (rview.getResourcetype().equals("2")) {
					// 测试
					view.putAttr("tip", "问答");
					ApiResult result = wcpConfig.getFqas(bindResource.getResourceurl(), null, null, null, 50);

					for (WdasJsonMap data : result.getData()) {
						Map<String, Object> node = new HashMap<String, Object>();
						node.put("TITLE", data.getObject("TITLE"));
						String note = data.getString("DOCDESCRIBE");
						if (note != null && note.length() > 128) {
							note = note.substring(0, 128) + "...";
						}
						node.put("NOTE", note);
						node.put("LINK", rview.getBaseurl() + "/webquest/fqa/Pub" + data.getObject("ID") + ".html");
						node.put("rview", rview);
						datas.add(node);
					}

				}

			}

			if (datas.size() <= 0) { // 自定義
				Map<String, Object> node = new HashMap<String, Object>();
				node.put("TITLE", rview.getResourcename());
				node.put("NOTE", bindResource.getNote());
				node.put("LINK", rview.getUrl());
				node.put("rview", rview);
				datas.add(node);
			} else {
				view.putAttr("rview", rview);
			}

			return view.putAttr("datas", datas).returnModelAndView("web-simple/commons/resourceLinkInfos");
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/commons/resourceLinkInfos");
		}
	}

}
